<template>
  <el-card class="box-card">
    <div>
      <el-form ref="form" :model="form" inline>
        <el-form-item prop="search">
          <el-input
            v-model="form.search"
            clearable
            @clear="search"
            style="width: 320px"
            prefix-icon="search"
            placeholder="输入主机名、实例ID、IP搜索"
          />
        </el-form-item>

        <el-form-item prop="区域">
          <el-select
            class="m-2"
            v-model="form.region_id"
            clearable
            @clear="search"
            @click="getRegions()"
            placeholder="区域"
          >
            <el-option
              v-for="item in regionOptions"
              :key="item.id"
              :label="`${item.city}-${item.region}`"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="success"
            icon="search"
            size="small"
            @click="search(form)"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    
          <el-row class="mb-4">
      <!--新建主机-->
      <el-dropdown style="margin-bottom: 12px">
        <el-button size="small" type="primary">
          <el-icon><plus /></el-icon>&nbsp;新建<el-icon class="el-icon--right"
            ><arrow-down
          /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="createDialogVisible = true"
              ><el-icon color="#409EFC" :size="20"><Edit /></el-icon
              >新建主机</el-dropdown-item
            >
            <el-dropdown-item @click="excelDialogVisible = true"
              ><el-icon color="#409EFC" :size="20"><Folder /></el-icon
              >Excel</el-dropdown-item
            >
            <el-dropdown-item @click="cloudDialogVisible = true"
              ><el-icon color="#409EFC" :size="20"><MostlyCloudy /></el-icon
              >云主机</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>

       <el-button
       style="margin-left: 12px"
        type="danger"
        icon="delete"
        :disabled="multipleSelection.length ? false : true"
        size="small"
        @click="deleteServers(form)"
        >删除</el-button>

        <!-- <el-button
          type="warning"
          icon="refresh"
          size="small"
          @click="search(form)"
          >一键同步</el-button
        > -->
          </el-row>

    <el-table
      ref="table"
      row-key="id"
      :data="tableData"
      highlight-current-rowd
      v-loading="listLoading"
      element-loading-text="拼命加载中"
      style="width: 100%; margin-bottom: 20px"
      :header-cell-style="{ background: '#fafafa', color: '#606266' }"
      @selection-change="handleSelectionChange"
    >
      <!-- 最左侧留出12px的宽度 -->
      <el-table-column 
      type="selection" 
      width="28" :reserve-selection="true" />

 
      <el-table-column type="expand">
        <template  #default="props">
            
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="版本"
              >{{ props.row.os_version }}
            </el-form-item>
            <el-form-item label="CPU">
              <span>{{ props.row.cpu }}</span>
            </el-form-item>
            <el-form-item label="内存">
              <span>{{ props.row.memory }}</span>
            </el-form-item>
            <el-form-item label="磁盘">
              <span>{{ props.row.disk }}</span>
            </el-form-item>
            <el-form-item label="备注">
              <span>{{ props.row.desc }}</span>
            </el-form-item>
            <el-form-item label="ssh账号">
              <span>{{ props.row.ssh_id.name }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ props.row.gmt_create }}</span>
            </el-form-item>
          </el-form>

        </template>
      </el-table-column>

      <el-table-column
        label="主机名称"
        prop="hostname"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="IP"
        prop="ip"
        align="center"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="弹性IP"
        prop="floatingip"
        min-width="100"
        show-overflow-tooltip
      />

      <el-table-column
        label="平台"
        align="center"
        prop="platform_id.name"
        show-overflow-tooltip
      />
       <el-table-column
        label="云账号"
        align="center"
        prop="platform_account_id.name"
        show-overflow-tooltip
      />
      
      <el-table-column
        label="区域"
        align="center"
        prop="region_id.region"
        min-width="100%"
        show-overflow-tooltip/>

       <!--操作栏-->
         <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
              <el-button
            type="success"
            size="small"
            @click="connectHost(scope.row)"
            >连接</el-button
          >
          <el-button
                  type="primary"
                  size="small"
                  @click="updateServer(scope.row)"
            >编辑</el-button>
          <el-button
                  type="danger"
                  size="small"
                  @click="deleteServer(scope.row)"
          >删除</el-button>

          <!-- <el-button
                  type="warning"
                  size="small"
                  @click="handleSync(scope.$index, scope.row)"
          >同步</el-button> -->

          <!-- <el-dropdown >
            <el-button size="small" type="primary" plain>
              更多
              <el-icon class="arrow-down"> </el-icon>
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item @click="updateServer(row)">
                编辑
              </el-dropdown-item>
              <el-dropdown-item @click="deleteServer(row)">
                删除
              </el-dropdown-item>
              <el-dropdown-item @click="cloneServer(row)">
                克隆
              </el-dropdown-item>
              <el-dropdown-item @click="handleSync(row)">
                同步配置
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->

        </template>
      </el-table-column>

      <!-- <el-table-column fixed="right" align="center" label="操作" width="250">
        <template #connect="scope">
          <el-button
            type="success"
            size="small"
            @click="connectHost(scope.row.id, scope.row.ssh_id)"
            >连接</el-button
          >

          <el-dropdown class="tools">
            <el-button size="small" type="primary" plain>
              更多
              <el-icon class="arrow-down"> </el-icon>
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item @click="updateServer(row)">
                编辑
              </el-dropdown-item>
              <el-dropdown-item @click="deleteServer(row)">
                删除
              </el-dropdown-item>
              <el-dropdown-item @click="cloneServer(row)">
                克隆
              </el-dropdown-item>
              <el-dropdown-item @click="handleSync(row)">
                同步配置
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column> -->



    </el-table>

    <!--分页组件-->
    <el-pagination
      :current-page="1"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="10"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <cuForm
      :dialog-visible="createDialogVisible"
      :dialog-detail="DialogDetail"
      :cur-id="curId"
      @close="close"
      @search="search"
    />
<createCloud :dialog-visible="cloudDialogVisible" @close="close" @search="search" />
<createExcel :dialog-visible="excelDialogVisible" @close="close" @search="search" />
<addCredential :dialog-visible="credentialVisible" :cur-id="curId" @close="close" @search="search" ></addCredential>

  </el-card>
</template>



<script>
import cuForm from "./components/cuForm";
import createCloud from "./components/createCloud";
import createExcel from "./components/createExcel";
import addCredential from "./components/credential";
import { getServers, deleteServer, deleteServers } from "@/api/asset/servers";
// import { getsshs } from "@/api/asset/ssh";
import { getRegions } from "@/api/cloudPlatform/region";

export default {
  name: "assets-server",
  components: {
    cuForm,
    createCloud,
    createExcel,
    addCredential,
  },
  data() {
    return {
      form: {
        page: 1,
        size: 10,
        search: "",
        ordering: "",
        region_id: "",
      },
      tableData: [],
      total: 0,

      //   statusOptions: [],
      listLoading: true,
      downloadLoading: false,
      autoWidth: true,
      multipleSelection: [],
      regionOptions: [],
      sshOptions: [],
      // cuForm数据
      DialogDetail: false, // 更多详情展示与隐藏
      createDialogVisible: false, //窗口打开
      excelDialogVisible: false, // 表格
      cloudDialogVisible: false, // 打开云主机
      credentialVisible: false, // 证书
      curId: null, // 当前row_id
      copy: false,
    };
  },
  created() {
    this.search();
  },
  methods: {
    search() {
      getServers(this.form).then((res) => {
        this.tableData = res.data.results;
        console.log("data:", res.data);
        this.listLoading = false;
        this.total = res.data.count;
      });
      console.log("search form", this.form);
    },
    // 查询凭证
    // getsshs () {
    //   getsshs().then((response) => {
    //     this.sshOptions = response.data.results;
    //     const passwd = [];
    //     for (let i in this.sshOptions) {
    //       passwd.push(
    //         this.sshOptions[i].name +
    //         "-" +
    //         this.sshOptions[i].authentication_type
    //       );
    //     }
    //     console.log("passwd 获取凭证:", passwd);
    //     console.log("sshOptions", this.sshOptions);
    //   });
    // },
    handleSync(row) {
      console.log("handleSync row:", row);
      // 如果主机有凭据直接同步
      if (row.ssh_id) {
        this.$axios
          .get("/asset/host_collect/", { params: { hostname: row.hostname } })
          .then((response) => {
            if (response.code == 20000) {
              this.$message.success(response.data.detail);
              // this.getData();
              this.search();
            } else {
              this.$message.error(response.data.detail);
            }
          });
      } else {
        this.credentialVisible = true;
      }
    },
    // 查询区域
    getRegions() {
      getRegions().then((res) => {
        res.data;
        this.regionOptions = res.data.results;
        const regions = [];
        for (let i in this.regionOptions) {
          regions.push(
            this.regionOptions[i].city + "." + this.regionOptions[i].region
          );
          console.log("regionsId:", i);
        }
        console.log("获取区域:", regions);
      });
    },

    // 重置
    resetForm() {
      console.log("重置按钮,刷新数据");
      this.$refs.form.resetFields();
      this.form.region_id = "";
      this.search();
    },
    // 删除服务器
    deleteServer(row) {
      this.$confirm("此操作将删除该服务器记录, 是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteServer(row.id).then((res) => {
          res.data;
          this.$message({
            message: "删除成功",
            type: "success",
          });
          // 刷新table
          this.search();
        });
      });
    },
    // 批量删除服务器
    deleteServers() {
      this.$confirm("此操作将删除选中服务器记录, 是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteServers(this.multipleSelectiondeleteIds).then((res) => {
          res.data;
          this.$message({
            message: "删除成功",
            type: "success",
          });
          // 刷新table
          this.search();
        });
      });
    },
    // 选项改变时触发
    handleSelectionChange(val) {
      // 批量ids
      const deleteIds = [];
      console.log("多选items",val)
      this.multipleSelection = val;
      console.log("this.multipleSelection ", this.multipleSelection )
       this.multipleSelection.forEach((data) => deleteIds.push(data.id));
      this.multipleSelectiondeleteIds = deleteIds;
    //   this.multipleSelection = val;
    },

    // cuForm子组件
    createServer() {
      this.$refs.form.resetFields();
      this.DialogVisible = true;
      const message = !this.DialogVisible ? "关闭" : "激活";
      console.log("点击触发Dialog", message + "窗口, 值:" + this.DialogVisible);
    },
    excelDialog() {
      this.excelDialogVisible = true;
    },
    updateServer(row) {
      this.curId = row.id;
      this.createDialogVisible = true;
      this.DialogDetail = true;
      console.log("this.curId +++++", this.curId);
    },
    cloneServer(row) {
      this.curId = row.id;
      this.createDialogVisible = true;
      this.DialogDetail = true;
    },
    close() {
      this.createDialogVisible = false;
      this.excelDialogVisible = false;
      this.cloudDialogVisible = false;
      this.credentialVisible = false;
      this.curId = null;
      const message = !this.createDialogVisible ? "关闭" : "激活";
      console.log(
        "接收子组件信息触发Dialog",
        message + "窗口, 值:" + this.createDialogVisible
      );
    },
    // 分页
    handleSizeChange(val) {
      this.form.size = val;
      this.search();
    },
    handleCurrentChange(val) {
      this.form.page = val;
      this.search();
    },
    getCredential() {
      this.$http.get("/config/credential/?page_size=50").then((res) => {
        this.credential = res.data.data;
      });
    },
    connectHost(row) {
      this.curId = row.id;
      console.log("this.curId +++++", this.curId,row);
      if (row.ssh_id) {
        const newpage = this.$router.resolve({
          path: "/webssh",
          name: "WSTerminal",
          params: {
            hostid: row.id,
          },
        });
        const newWindow = window.open(newpage.href, "_blank");
        newWindow.hostid = row.id;
        console.log("window.hostid:",newWindow.hostid)
      } else {
        this.credentialVisible = true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-tooltip__popper {
  max-width: 200%;
}
.demo-table-expand {
  font-size: 0;
}
.app-container ::v-deep .demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.tools {
  margin-left: 10px;

  // text-align: center;
}
</style>
